const chalk = require("chalk");
const ora = require("ora");
const emoji = require("node-emoji");
const { name } = require("../package.json");
const likeLinux = process.env.TERM === "cygwin" || process.platform !== "win32";

function getType(agr) {
  return Object.prototype.toString
    .call(agr)
    .split(/\s/)[1]
    .slice(0, -1)
    .toLowerCase();
}

function stringify(value) {
  const type = getType(value);
  if (type === "object") {
    let val = {};
    Object.entries(value).forEach(i => {
      const [k, v] = i;
      const type = getType(v);
      if (type === "function" || type === "asyncfunction") {
        val[`${k}-${type}`] = v.toString();
      } else {
        val[`${k}-${type}`] = v;
      }
    });
    return val;
  }
  return JSON.stringify(value);
}

function Spinner(color) {
  let opt = likeLinux
    ? {
        spinner: {
          interval: 125,
          frames: ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]
        }
      }
    : "";
  const spinner = ora(opt).start();
  spinner.color = color;
  return spinner;
}

const emoji_get = emoji.get.bind(emoji);
emoji.get = function() {
  return !likeLinux ? "·" : emoji_get.apply(emoji, arguments);
};

function log() {
  console.log.apply(console, arguments);
}

log.error = function(msg, exit) {
  log(chalk.gray(`[${name}]:`, chalk.red(msg)));
  exit && process.exit(0);
};

log.warn = function(msg) {
  log(chalk.yellow(msg));
};

log.info = function(msg) {
  log(chalk.greenBright(msg));
};

module.exports = {
  log,
  getType,
  Spinner,
  emoji,
  stringify
};
